Type Casting

Sometimes we find ourselves in a situation where we need the value of an already existing variable in a different data type than the one with which it was defined. This is where type casting comes in. Type casting is an approach which allows changing the data type of a variable or an expression from one to another. One thing to remember is that not every data type can be converted to a data type of choice. Let’s look at the type casting flow in Scala to better understand which data type can be converted to which data type.

Byte —> Short —> Int —> Long —> Float —> Double

                  ^
                  |
                 Char

The arrows denote that a given value type on the left-hand side of the arrow can be promoted to the right-hand side.
For example, a Byte can be promoted to a Short. The opposite, however, is not true. Scala will not allow us to assign in the opposite direction:

object Demo {
def main(args: Array[String]) {
val oldType: Long = 926371285
val newType: Float = oldType
// Driver Code
println(oldType)
println(newType)
}
}

object Demo {
def main(args: Array[String]) {
val oldType: Long = 926371285
val newType: Float = oldType
val newOldType: Long = newType
// Driver Code
println(oldType)
println(newType)
println(newOldType)
}
}

type mismatch;
 found   : Float
 required: Long
 val newOldType: Long = newType

object Demo {
def main(args: Array[String]) {
val oldType: Char = 'A'
val newType: Int = oldType
// Driver Code
println(oldType)
println(newType)
}
}

A

65

Types of Type Casting

There can be two types of typecasting as all programming languages have,

  • Implicit type casting
  • Explicit type casting
Implicit Type Casting


No comments:

Post a Comment